package com.common.www.controller.tabulation;


import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.project.Project;
import com.common.www.bean.entity.tabulation.XfgcBidBaseTabulation;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.project.ProjectService;
import com.common.www.service.tabulation.XfgcBidBaseTabulationService;
import com.common.www.service.tabulation.XfgcSummaryService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.office.ImportExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/xfgcBidBaseTabulation"})
@Api(tags = "MGT 后台消防工程标底清单管理")
public class MGTXfgcBidBaseTabulationController extends DefaultCrudController<XfgcBidBaseTabulation, Long> {

    @Autowired
    private XfgcBidBaseTabulationService xfgcBidBaseTabulationService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private XfgcSummaryService xfgcSummaryService;

    protected IBaseService<XfgcBidBaseTabulation, Long> getService() {
        return xfgcBidBaseTabulationService;
    }


    @ApiOperation("保存单条标底清单")
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(@RequestBody XfgcBidBaseTabulation xfgcTabulation) {
        if (xfgcTabulation.getId() != null) {
            xfgcBidBaseTabulationService.calculation(xfgcTabulation);
            xfgcBidBaseTabulationService.save(xfgcTabulation);
        }
        return R.ok(xfgcTabulation);
    }


    @ApiOperation("批量删除（逻辑删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids) {
        if (ParamsUtils.isInputEmpty(ids)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        xfgcBidBaseTabulationService.deleteByIdsLogic(ids);
        return R.ok();
    }

    @ApiOperation("按项目删除对应标底信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "bidType", value = "String", defaultValue = ""),
    })
    @Transactional
    @RequestMapping(value = "/deletesByProjectToType", method = RequestMethod.POST)
    public Result deletesByProjectToType(Long projectId) {
        if (ParamsUtils.isInputEmpty(projectId)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        xfgcBidBaseTabulationService.getRepository().deleteByProjectId(projectId);
        xfgcSummaryService.getRepository().deleteByProjectIdAndJieDuan(projectId, 1);
        return R.ok();
    }


    @ApiOperation(value = "导入标底清单", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/importBd", produces = {"application/json"}, method = RequestMethod.POST)
    public Result importBd(MultipartFile file, Long projectId) throws Exception {
        Project project = projectService.findOne(projectId);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook workbook = new ImportExcelUtil().getWorkbook(inputStream, fileName);
        List<XfgcBidBaseTabulation> listImport = xfgcBidBaseTabulationService.importSimulate(workbook);
        //整理listImport的数据格式
        List<XfgcBidBaseTabulation> listArrange = new ArrayList<>();

        String itemName = null;
        String lastNonNullOriginalTypeName = null;
        String zbTwo = null;
        String codeNumberType = null;
        for (XfgcBidBaseTabulation listObj : listImport) {
            String originalTypeName = listObj.getName();
            String currentCodeNumber = listObj.getCodeNumber();
            if (StringUtils.isNotEmpty(currentCodeNumber) && ("HZ".equals(currentCodeNumber) || "GB".equals(currentCodeNumber) || "XHS".equals(currentCodeNumber)
                    || "PL".equals(currentCodeNumber) || "YY".equals(currentCodeNumber) || "MHQ".equals(currentCodeNumber)
                    || "JL".equals(currentCodeNumber) || "QT".equals(currentCodeNumber) || "FHM".equals(currentCodeNumber)
                    || "DYJK".equals(currentCodeNumber) || "HZJK".equals(currentCodeNumber) || "YJZM".equals(currentCodeNumber)
                    || "LX".equals(currentCodeNumber) || "XFJC".equals(currentCodeNumber) || "KZZJ".equals(currentCodeNumber)
                    || "WB".equals(currentCodeNumber) || "ZB".equals(currentCodeNumber))) {
                codeNumberType = currentCodeNumber;
                lastNonNullOriginalTypeName = originalTypeName;
                if ("ZB".equals(currentCodeNumber)) {
                    itemName = originalTypeName;
                }
            } else {
                if (lastNonNullOriginalTypeName != null && "增补清单".equals(itemName)) {
                    //增补清单的下一级
                    if (listObj.getCodeNumber() != null && listObj.getCodeNumber().length() > 2
                            && listObj.getCodeNumber().charAt(0) == 'Z' && listObj.getCodeNumber().charAt(1) == 'B'
                            && !listObj.getCodeNumber().matches(".*[0-9-].*")) {
                        zbTwo = listObj.getName();
                    } else {
                        listObj.setNameType1(itemName);
                        listObj.setNameType2(zbTwo);
                    }
                } else {
                    listObj.setNameType1(lastNonNullOriginalTypeName);
                }
                if (currentCodeNumber != null && !currentCodeNumber.isEmpty() && currentCodeNumber.contains("-")) {
                    listObj.setFlag(1);
                    listObj.setProject(project);
                    listObj.setJieDuan(1);
                    listObj.setCodeNumberType(codeNumberType);
                    listArrange.add(listObj);
                }

            }
        }

        //计算 税金、综合单价
        for (XfgcBidBaseTabulation tabulation : listArrange) {
            xfgcBidBaseTabulationService.calculation(tabulation);
        }

        if (listArrange.size() > 0) {
            //先删除原来的，再添加
            List<XfgcBidBaseTabulation> bidBaseTabulationList = xfgcBidBaseTabulationService.getRepository().findByFlagAndProjectId(1, projectId);
            for (XfgcBidBaseTabulation bidBaseTabulation : bidBaseTabulationList) {
                bidBaseTabulation.setFlag(0);
                xfgcBidBaseTabulationService.save(bidBaseTabulation);
            }
            if (bidBaseTabulationList.size() > 0) {
                xfgcSummaryService.getRepository().deleteByProjectIdAndJieDuan(bidBaseTabulationList.get(0).getProject().getId(), 1);
            }
        }
        xfgcBidBaseTabulationService.save(listArrange);
        //清单关联信息保存
        xfgcSummaryService.saveCorrelationBd(project, 1, fileName);
        return R.ok();
    }

    @ApiOperation("导出标底清单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/exportXfgcBd", method = RequestMethod.GET)
    public Result exportXfgcBd(Long projectId) {
        Project project = projectService.findOne(projectId);
        String fileName = project.getName() + "标底";
        XSSFWorkbook workbook = xfgcBidBaseTabulationService.exportQd(project, fileName);
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("application/binary;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + URLEncoder.encode(fileName + "-导出.xlsx", "UTF-8"));
            response.setHeader("Pragma", "No-cache");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.fail("导出错误");
    }


    @ApiOperation(value = "查询标底信息(按分项查询)", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/getBidBaseTabList", produces = {"application/json"}, method = RequestMethod.POST)
    public Result getBidBaseTabList(Long projectId) {
        HashMap hashMap = new HashMap();
        hashMap.put("project.id", projectId);
        List<XfgcBidBaseTabulation> xfgcBidBaseTabulationList = xfgcBidBaseTabulationService.getListLogic(hashMap, null);

        // 按name属性分组
        Map<String, List<XfgcBidBaseTabulation>> nameType1List = xfgcBidBaseTabulationList.stream()
                .collect(Collectors.groupingBy(XfgcBidBaseTabulation::getNameType1));

        List<Map<String, Object>> mapList = new ArrayList<>();
        Integer indexName = 0;
        for (Map.Entry<String, List<XfgcBidBaseTabulation>> item : nameType1List.entrySet()) {
            indexName++;
            String nameType1 = item.getKey();
            List<XfgcBidBaseTabulation> value = item.getValue();

            XfgcBidBaseTabulation newT = xfgcBidBaseTabulationService.calculationSubtotal(value);
            value.add(0, newT);

            Map<String, Object> tempTabulation = new HashMap<>();
            tempTabulation.put("indexName", indexName);
            tempTabulation.put("nameType1", nameType1);
            tempTabulation.put("value", value);
            mapList.add(tempTabulation);
        }

        return R.ok(mapList);
    }

}
